import { unquote } from "./formatString.js";

// 字符串转整数, 不合法抛出异常
function parseIntNumber(inString: string): number {
  inString = unquote(inString);
  if (!/^[-+]?\d+$/.test(inString)) throw new Error(`"${inString}" 不是一个合法的整数`);
  return parseInt(inString);
}

// 字符串转浮点数, 不合法抛出异常
function parseFloatNumber(inString: string): number {
  inString = unquote(inString);
  if (!/^[+-]?(\d+\.?\d*|\.\d+)([eE][+-]?\d+)?$/.test(inString))
    throw new Error(`"${inString}" 不是一个合法的浮点数`);
  return parseFloat(inString);
}

// 字符串转布尔值, 不合法抛出异常
function parseBoolean(inString: string): boolean {
  inString = inString.toLowerCase();
  switch (inString) {
    case "true":
    case "1":
      return true;
    case "false":
    case "0":
      return false;
  }
  throw new Error(`"${inString}" 不是一个合法的布尔值`);
}

// 解析行动参数
export function parseActArg(arg: string, type: "int" | "float" | "bool" | "string"): any {
  switch (type) {
    case "int":
      return parseIntNumber(arg);
    case "float":
      return parseFloatNumber(arg);
    case "bool":
      return parseBoolean(arg);
    case "string":
      return unquote(arg);
  }
  throw new Error(`未知的类型: ${type}`);
}

export const ActRegex: RegExp = new RegExp(`&(\\w+)(?:[(（)]([^)）]*)[)）])?`, "u");

// 从字符串中解析行动名称和参数
export function parseAct(inString: string): { actName: string; actArgs: Array<string> } | null {
  const globalMatch = inString.match(new RegExp(ActRegex.source, "g"));
  if (globalMatch && globalMatch.length > 1) throw new Error("只允许一个行动调用");

  const match = inString.match(ActRegex);
  if (!match) return null;

  const actName = match[1] as string;
  const result = {
    actName: actName,
    actArgs: [] as Array<string>,
  };

  if (match[2]) {
    const actArgString = match[2] as string;
    result.actArgs.push(
      ...actArgString
        ?.split(/[,，]/)
        .map((arg) => arg.trim())
        .filter((arg) => arg.length > 0)
    );
  }

  return result;
}
